<?php

namespace App\Http\Controllers\Api;

use App\Event;
use App\Http\Controllers\Controller;
use App\Message;
use App\User;
use App\UserEvent;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class EventController extends Controller
{
    public function index(){
        $events = Event::all()->makeHidden('client_id','photo');
        return $this->success($events);
    }
    public function show(Event $event){
        $event->employees->makeHidden(['pivot','is_admin'])->each(function ($item){
            $item->response = $item->pivot->response;
        });

        $event->makeHidden('client_id');
        $event->client ;

        return $this->success($event);
    }
    public function create(Request $request){
        $this->is_admin();
        $validate = $this->validate($request,[
            'name'=>'required',
            'type'=>'required|in:Course,Training',
            'address'=>'required',
            'permission'=>'required|in:Public,Private',
            'photo'=>'required|image',
            'date'=>'required|date|after_or_equal:tomorrow',
            'client_id'=>'required|exists:clients,id',
            'employee_ids'=>'required'
        ]);

        $employee_ids = json_decode($validate['employee_ids']);


        if (!is_array($employee_ids)) return $this->error_422();

        foreach ($employee_ids as $employee_id){
            if (!User::where('scope',$validate['type'])->find($employee_id)) return $this->error_422();
        }

        $file = $request->file('photo')->store('/public/upload/event/'.Carbon::now()->format('Y-m-d'));
        $photo = Storage::url($file);

        $event = new Event($validate);
        $event->photo = $photo;
        $event->code = Str::random(8);
        $event->save();

        foreach ($employee_ids as $employee_id){
            $user_event_mapping = new UserEvent([
                'event_id'=>$event->id,
                'user_id'=>$employee_id
            ]);
            $user_event_mapping->save();
        }

        return $this->success(['id'=>$event->id]);
    }
    public function delete(Event $event){
        $this->is_admin();

        $event->delete();
        return $this->success();
    }
    public function employees(Request $request,Event $event){
        $this->is_admin();
        $validate = $this->validate($request,[
            'employee_ids'=>'required|array'
        ]);

        $employee_ids = array_keys(array_flip($validate['employee_ids']));
        $origin_employee_ids = $event->employees()->get()->pluck('id')->toArray();
        foreach($employee_ids as $employee_id){
            $key = array_search($employee_id,$employee_ids);
            if ($key === false){
                $user_event_mapping = new UserEvent([
                    'event_id'=>$event->id,
                    'user_id'=>$employee_id
                ]);
                $user_event_mapping->save();
            }else{
                unset($origin_employee_ids[$key]);
            }
        }

        foreach ($origin_employee_ids as $employee_id){
            UserEvent::where('event_id',$event->id)->where('user_id',$employee_id)->delete();
        }

        return $this->success();
    }
    public function client(Request $request,Event $event){
        $validate = $this->validate($request,[
            'client_id'=>'required|exists:clients,id'
        ]);

        $event->client_id = $validate['client_id'];
        $event->save();

        return $this->success();
    }
    public function unreplied(){
        $unreplied_event_ids = Message::where('is_reply',0)->where('reply_status',0)->get()->pluck('event_id')->toArray();
        $event_ids = array_unique($unreplied_event_ids);
        $events = Event::whereIn('id',$event_ids)->get()->makeHidden(['code','type','address','permission','date','status','photo','client_id','messages','client'])->each(function ($item){
            $last_message =  $item->messages()->orderBy('created_datetime','DESC')->first()->makeHidden('event_id','created_datetime');
            $item->last_message = $last_message;
            $item->message_count = $item->messages()->count();
            $item->corporate_name = $item->client->corporate_name;
        });


        return $this->success($events);
    }
    public function preview($event_code){
        $event = Event::whereRaw('BINARY(code = ?)',$event_code)->first();
        if (empty($event))throw  new ModelNotFoundException();
        $event->makeHidden(['code','permission','client_id','status','client']);
        $event->corporate_name = $event->client->corporate_name;

        return $this->success($event);
    }
    public function preview_phone($event_code,$event_phone){
        $event = Event::whereRaw('BINARY(code = ? )',$event_code)->first();
        if (empty($event))throw  new ModelNotFoundException();
        if ($event_phone != $event->client->phone) return $this->error_422('the phone number does not match the event code');

        foreach ($event->employees as $employee){
            $employee->response = $employee->pivot->response;
        }
        $event->makeHidden(['code','client_id']);
        $event->employees->makeHidden(['is_admin','pivot','scope']);

        return $this->success($event);
    }
    public function check_code(Event $event,$event_code){
        if (strtoupper($event->code) != strtoupper($event_code)) return $this->error_401('the event code is not correct');
        return $this->success();
    }
    public function event_list(){
        $events = Event::all()->makeHidden(['client_id','code','status','address']);

        return $this->success($events);
    }
}
